require 'hpricot'

namespace :data do
	task :create_super_user => :environment do
		puts "login: admin; pass: ;ehyfk"
		User.delete_all("login = 'admin'")
		user = User.new({:login=>"admin", :name=>"Adminnistrator", :password=>";ehyfk", :password_confirmation=>";ehyfk", :email=>"admin@mail.com"})
		user.roles << Role.find_by_ident(Role::ADMIN) 
		user.activated_at = Time.now
  	user.save!
	end

	task :activate_all => :environment do
		puts "Activate users:"
		User.find(:all, :conditions => {:activated_at => nil}).each do |user|
			user.activated_at = Time.now
  		user.save!
			puts user.login
		end
	end
	
	task :create_roles => :environment do
		Role.destroy_all
		Role.create!(:name=>"Администратор", :ident=>Role::ADMIN)
		Role.create!(:name=>"Модератор", :ident=>Role::MODERATOR)
		Role.create!(:name=>"Пользователь", :ident=>Role::DEFAULT)
	end
	
	task :create_countries => :environment do
		file = "#{RAILS_ROOT}/db/countries.xml"
		return unless File.exist?(file)
		xml = Hpricot(File.open(file).read)
		xml.search("/countries/row").each do |country|
			Country.create(:name=>country.at('/name').inner_text.strip, :code=>country.at("/code").inner_text.strip)
		end
	end
	
	task :setup => [:create_roles, :create_super_user, :create_countries]
	
	task :rebuild_index => :environment do
		idx_post = ActsAsFerret.get_index_for Post
		idx_article = ActsAsFerret.get_index_for Article
		idx_community = ActsAsFerret.get_index_for Community
		
		idx_post.rebuild_index
		idx_article.rebuild_index
		idx_community.rebuild_index
	end
	
	task :fix_community => :environment do
		@communities = Community.find(:all, :conditions=>"user_id IS NULL")
		@communities.each do |c|
			c.user = c.users.first
			c.user ||= User.find_by_login('admin')
			c.save!
		end
	end

end
